// amis 环境配置
import axios, {AxiosRequestConfig} from 'axios';
import { message } from 'antd';
import { render as renderAmis } from 'amis-core';
import {alert, confirm} from 'amis-ui';
import {AlertComponent, fetcherResult, RenderOptions, ToastComponent} from 'amis';
import useReq from "@/hooks/useReq";
import {AmisSchema} from "@/utils/amisUtils.ts";
import {FetcherConfig} from "amis-core/lib/factory";

export default function useAmis(schema: AmisSchema) {
  const [messageApi, contextHolder] = message.useMessage();
  const {request} = useReq();

  const env: RenderOptions = {
    // 下面三个接口必须实现
    fetcher: async ({
                url, // 接口地址
                method, // 请求方法 get、post、put、delete
                data, // 请求数据
                config, // 其他配置
              }: FetcherConfig) => {
      const newConfig: AxiosRequestConfig = (config as AxiosRequestConfig)|| {};
      let newData: object|null = data as object|null;

      if (method === 'get' || method === 'delete') {
        if (newData) {
          newConfig.params = newData;
          newData = null;
        }
      } else if (newData && newData instanceof FormData) {
        newConfig.headers = {
          ...newConfig.headers,
          'Content-Type': 'multipart/form-data'
        }
        newConfig.data = newData;
      } else if (
        newData &&
        !(newData instanceof Blob) &&
        !(newData instanceof ArrayBuffer)
      ) {
        newConfig.headers = {
          ...newConfig.headers,
          'Content-Type': 'application/json'
        }
        newConfig.data = newData;
      }
      const resp = await request(url, {...newConfig, method});
      return {
        status: resp.status,
        data: resp.data,
      } as fetcherResult
    },
    isCancel: (value) => axios.isCancel(value),
    notify: (
      type: 'info' | 'success' | 'error' | 'warning' | 'loading' /**/,
      msg: string /*提示内容*/
    ) => {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      messageApi.open({
        content: msg,
        type,
      }).then(() => {return});
    },
    alert: (content, title) => {
      alert(content, title).catch(() => {return})
    },
    confirm: async (content, title) => {
      return (await confirm(content, title)) as boolean
    }
  };

  const Dom = renderAmis(
    schema,
    {},
    env
  );

  return () => (
    <>
      <ToastComponent key="toast" position={'top-right'} />
      <AlertComponent key="alert" />
      {Dom}
      {contextHolder}
    </>
  );
}